package com.quanquan.store.message;

import com.quanquan.store.service.ShoppingKillTradingRecordService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;


/**
 * 功能描述:秒杀商品订单队列
 *
 * @ClassName: MqSendCouponReceiver
 * @Author: xiaoqianh丶
 * @Date: 2019-04-05 23:02
 * @Version: V1.0
 */
@Slf4j
@Component
public class MqShoppingKillRecordReceiver {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    private final ShoppingKillTradingRecordService shoppingKillTradingRecordService;

    public MqShoppingKillRecordReceiver(ShoppingKillTradingRecordService shoppingKillTradingRecordService) {
        this.shoppingKillTradingRecordService = shoppingKillTradingRecordService;
    }

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "shoppingKillRecord",
                    durable = "true"),
            exchange = @Exchange(value = "shoppingKill.exchange",
                    type = "topic"),
            ignoreDeclarationExceptions = "true",
            key = "shoppingKill.#")})
    @RabbitHandler
    public void monitoringShoppingKill(Message message, Channel channel) throws IOException {
        //会员id
        String userId = Objects.requireNonNull(message.getHeaders().get("userId")).toString();
        //秒杀商品的id
        String shoppingKillId = Objects.requireNonNull(message.getHeaders().get("shoppingKillId")).toString();
        String uuid = Objects.requireNonNull(message.getHeaders().get("uuid")).toString();

        //手工ack
        long deliveryTag = Long.parseLong(Objects.requireNonNull(message.getHeaders().get(AmqpHeaders.DELIVERY_TAG)).toString());
        channel.basicAck(deliveryTag, false);


        //生成订单页面
        shoppingKillTradingRecordService.createRecord(userId,shoppingKillId,uuid);
    }

}